﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;
using nplJobsDAL;

using nplJobsCommon.Common;
using nplJobsCommon.JobSeeker;
using nplJobsCommon.Employeer;

using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using Elmah;
using System.Text;
using System.Configuration;

public partial class Employeer_SearchCVDetails : BasePage // System.Web.UI.Page
{
    protected JobSeeker jobSeekerBind { get; set; }
    protected string jobSeekerAddress { get; set; }

    public string ModifiedON;
    public string jobtitle;
    public string degree;
    public string institution;
    public string experience;
    public string companyName;
    public string gender;
    public string nationality;
    public string maritialStatus;
    public string age;
    public string photoPath;
    public List<ProfessionalInfo> listProfessionalInfo;
    public List<EducationInfo> eInfo;
    static Guid userID;
    static List<EmployeerContactPerson> employeerContactPerson = null;
    static List<Employeer> employeer = null;

    protected void Page_Load(object sender, EventArgs e)
    {

        base.ReloadUserInfoSession();
        if (!Page.IsPostBack)
        {
            try
            {
                Page.Title = "Search cv details";

                if (!string.IsNullOrEmpty(Page.Request["id"]))
                {
                    #region Databind Repeater Controls
                    nplJobsBLL.ProcessSelectJobSeeker.ProcessSelectJobSeeker jobSeekerList = new nplJobsBLL.ProcessSelectJobSeeker.ProcessSelectJobSeeker();
                    jobSeekerList.JobSeekerID = new Guid(Page.Request["id"].ToString());
                    jobSeekerList.invoke();



                    List<JobSeeker> listJobSeeker = jobSeekerList.JobSeeker;
                    jobSeekerBind = listJobSeeker[0];

                    if (jobSeekerBind != null)
                    {
                        List<string> address = new List<string>();

                        if (!string.IsNullOrEmpty(jobSeekerBind.PostalAddress))
                        {
                            address.Add(jobSeekerBind.PostalAddress);
                        }
                        if (!string.IsNullOrEmpty(jobSeekerBind.City))
                        {
                            address.Add(jobSeekerBind.City);
                        }
                        if (!string.IsNullOrEmpty(jobSeekerBind.District))
                        {
                            address.Add(jobSeekerBind.District);
                        }
                        if (!string.IsNullOrEmpty(jobSeekerBind.Country))
                        {
                            address.Add(jobSeekerBind.Country);
                        }

                        string strAddress = string.Join(", ", address.ToArray());

                        if (!string.IsNullOrEmpty(strAddress))
                        {
                            lblAddress.Text = strAddress;
                        }


                        if (!string.IsNullOrEmpty(jobSeekerBind.Photo))
                            photoPath = Helper.ResolveUrl("~/UploadedImage/" + jobSeekerBind.Photo);
                        else
                            photoPath = Helper.ResolveUrl("~/img/candidate-cv-photo.png");

                        //int days = (System.DateTime.Today.Subtract(this.jobSeekerBind.Modifiedon)).Days / (366 / 12);
                        //ModifiedON = days > 0 ? days.ToString() + " Months  ago" : "Less than a month ago";

                        double d = (DateTime.Now - this.jobSeekerBind.Modifiedon).TotalDays;

                        double result = 0;

                        if (d > 0)
                        {
                            if (d < 30)
                            {
                                result = d;
                                string _months = "Less than a month ago";
                                ModifiedON = _months;
                            }
                            else if (d > 30 && d < 365)
                            {
                                result = Math.Floor(d / 30);
                                string _months = result.ToString() + " month(s) ago";
                                ModifiedON = _months;
                            }
                            else if (d >= 365)
                            {
                                result = Math.Floor(d / 365);
                                string _years = result.ToString() + " year(s) ago";
                                ModifiedON = _years;
                            }
                        }
                        else
                        {
                            int resultantDay = 0;
                            string days = string.Empty;

                            if (resultantDay == 0)
                                days = "Within last 24 hours";
                            else
                                days = resultantDay.ToString() + " day(s) ago";

                            ModifiedON = days;
                        }


                        int years = (System.DateTime.Today.Subtract(this.jobSeekerBind.DOB)).Days / 365;
                        age = years.ToString();

                        nplJobsBLL.Common.ProcessGender pg = new nplJobsBLL.Common.ProcessGender();
                        pg.invoke();
                        List<Gender> listGender = pg.Gender;
                        if (jobSeekerBind.GenderID == 1 || jobSeekerBind.GenderID == 2)
                            gender = listGender.Find(x => x.ID == jobSeekerBind.GenderID).GenderName;

                        nplJobsBLL.Common.ProcessMaritalStatus pm = new nplJobsBLL.Common.ProcessMaritalStatus();
                        pm.invoke();
                        List<MaritalStatus> listMaritialStatus = pm.MaritalStatus;
                        if (jobSeekerBind.MaritalStatusID > 0)
                            maritialStatus = listMaritialStatus.Find(y => y.ID == jobSeekerBind.MaritalStatusID).Status;

                        nplJobsBLL.Common.ProcessNationality pn = new nplJobsBLL.Common.ProcessNationality();
                        pn.invoke();
                        List<Nationality> listNationality = pn.Nationality;
                        if (jobSeekerBind.NationalityID > 0)
                            nationality = listNationality.Find(x => x.ID == jobSeekerBind.NationalityID).NationalityName;

                        nplJobsBLL.ProcessJobSeeker.ProcessSelectProfessionalInfo jobseekerProfessionalInfo = new nplJobsBLL.ProcessJobSeeker.ProcessSelectProfessionalInfo();
                        jobseekerProfessionalInfo.JobseekerID = new Guid(Page.Request["id"].ToString());
                        jobseekerProfessionalInfo.ProfessionalInfoID = -1;

                        jobseekerProfessionalInfo.invoke();
                        listProfessionalInfo = jobseekerProfessionalInfo.ProfessionalInfo;

                        nplJobsBLL.ProcessJobSeeker.ProcessSelectEducationalInfo educationalInfo = new nplJobsBLL.ProcessJobSeeker.ProcessSelectEducationalInfo();
                        educationalInfo.EducationalInfoID = -1;
                        educationalInfo.JobseekerID = new Guid(Page.Request["id"].ToString());
                        educationalInfo.invoke();
                        eInfo = educationalInfo.EducationalInfo;


                        nplJobsBLL.ProcessJobSeeker.ProcessSelectJobSeekerLanguageProficiency langlInfo = new nplJobsBLL.ProcessJobSeeker.ProcessSelectJobSeekerLanguageProficiency();
                        langlInfo.JobSeekerID = new Guid(Page.Request["id"].ToString());
                        langlInfo.invoke();
                        List<JobSeekerLanguageProficiency> lInfo = langlInfo.JobSeekerLanguageProficiency;



                        string[] skills = null;
                        if (!string.IsNullOrEmpty(jobSeekerBind.Skills))
                        {
                            skills = jobSeekerBind.Skills.Trim().Split(',');
                        }

                        string[] qualifications = null;
                        if (!string.IsNullOrEmpty(jobSeekerBind.Qualifications))
                        {
                            qualifications = jobSeekerBind.Qualifications.Trim().Split('~');
                        }

                        int totalExperience = 0, months = 0;

                        if (listProfessionalInfo.Count != 0)
                        {
                            jobtitle = listProfessionalInfo[0].Title;
                            companyName = listProfessionalInfo[0].CompanyName;

                            foreach (ProfessionalInfo pf in listProfessionalInfo)
                            {
                                int m = (pf.ToDate - pf.FromDate).Days / 30;
                                months += m;
                            }

                            if (months > 12)
                            {
                                totalExperience = months / 12;
                                experience = totalExperience.ToString() + " Year(s)";
                            }
                            else
                            {
                                totalExperience = months;
                                experience = totalExperience.ToString() + " Month(s)";
                            }
                        }
                        if (eInfo.Count != 0)
                        {
                            degree = eInfo[0].Degree;
                            institution = eInfo[0].InstitutionName;
                        }
                        this.DataBind();

                        RepeaterProfessionalDetails.DataSource = listProfessionalInfo != null ? listProfessionalInfo.OrderBy(p => p.CurrentPosition ? 0 : 1) : null;
                        RepeaterProfessionalDetails.DataBind();

                        RepeaterEducationalDetails.DataSource = eInfo != null ? eInfo.OrderByDescending(edu=>edu.FromDate) : null;
                        RepeaterEducationalDetails.DataBind();

                        List<string> _qualifications = qualifications != null ? qualifications.Where(s => s != "").ToList() : null;

                        RepeaterQualification.DataSource = _qualifications;
                        RepeaterQualification.DataBind();

                        List<string> _skills = skills != null ? skills.Where(s => s != "").ToList() : null;
                        LoadSkills(_skills);
                        //RepeaterSkillsDetails.DataSource = _skills;
                        //RepeaterSkillsDetails.DataBind();

                        RepeaterLanguageDetails.DataSource = lInfo;
                        RepeaterLanguageDetails.DataBind();
                    #endregion


                        toEmailAddress.Text = this.jobSeekerBind.Email;
                        employeerContactPerson = employeeContact();

                        foreach (EmployeerContactPerson ecp in employeerContactPerson)
                        {
                            empEmailList.Items.Add(ecp.Email.ToString());
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
    }

    #region LoadSkills
    /// <summary>
    /// This is a quick change this code will have to be changed with a better implementation
    /// </summary>
    /// <param name="skills"></param>
    private void LoadSkills(List<string> skills)
    {
        if (skills != null && skills.Any())
        {

            divAllSkills.Visible = true;
            int count = 0;

            StringBuilder sbSkills = new StringBuilder();
            StringBuilder sbAllSkills = new StringBuilder();
            sbAllSkills.Append("<div class=\"col-md-10\">");

            //foreach (var skill in skills)
            //{
            //    count = count + 1;

            //    if (count == 1)
            //    {
            //        sbSkills = new StringBuilder();
            //        //sbSkills.Append("<div class=\"col-md-4\">");
            //        //sbSkills.Append("<ul class=\"skill-list\">");
            //    }
            //    if (count == skills.Count())
            //    {
            //        if (count == skills.Count())
            //        {
            //            sbSkills.Append("<li><span>" + skill + "</span></li>");

            //            //sbSkills.Append(" </ul>");
            //            //sbSkills.Append(" </div>");
            //            sbAllSkills.Append(sbSkills.ToString());
            //        }
            //    }
            //    else
            //    {
            //        sbSkills.Append("<li><span>" + skill + "</span></li>");
            //    }
            //}

            skills.ToList().Sort();
            count = skills.Count();

            if (count <= 20)
            {
                List<string> skillsSet = skills.ToList().GetRange(0, count - 1);

                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
            }
            else if (count > 20 && count <= 40)
            {
                List<string> skillsSet = new List<string>();
                skillsSet = skills.ToList().GetRange(0, 19);
                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
                skillsSet = new List<string>();
                skillsSet = skills.ToList().GetRange(20, 19);
                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
            }
            else if (count > 40)
            {
                List<string> skillsSet = new List<string>();
                skillsSet = skills.ToList().GetRange(0, 19);
                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
                skillsSet = new List<string>();
                skillsSet = skills.ToList().GetRange(20, 19);
                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
                skillsSet = new List<string>();
                int tCount = skills.Count() - 40;
                skillsSet = skills.ToList().GetRange(40, tCount);
                if (skillsSet.Any())
                {
                    GetSkill(sbSkills, skillsSet);
                }
            }

            sbAllSkills.Append(sbSkills);

            sbAllSkills.Append(" </div>");

            if (sbAllSkills != null)
            {
                divSkills.InnerHtml = sbAllSkills.ToString();
            }
        }
        else
        {
            divAllSkills.Visible = false;
        }
    }

    private static void GetSkill(StringBuilder sbSkills, List<string> skillsSet)
    {
        sbSkills.Append("<div class=\"col-md-4\">");
        sbSkills.Append("<ul class=\"skill-list\">");

        foreach (var skill in skillsSet)
        {
            sbSkills.Append("<li><span>" + skill + "</span></li>");
        }
        sbSkills.Append(" </ul>");
        sbSkills.Append(" </div>");
    }

    //private void SkillsSetTwo(List<string> skills, StringBuilder sbSkills)
    //{
    //    foreach (var skill in skills)
    //    {
    //        sbSkills.Append("<li><span>" + skill + "</span></li>");
    //    }

    //    if (!string.IsNullOrEmpty(sbSkills.ToString()))
    //    {
    //        divSkillsSet2.Attributes.Add("display", "");
    //        ulSkillsSet2.InnerHtml = sbSkills.ToString();
    //    }
    //}


    #endregion


    private static List<EmployeerContactPerson> employeeContact()
    {
        MembershipUser currentUser = (MembershipUser)HttpContext.Current.Session["userInfo"];
        try
        {
            if (currentUser != null)
            {
                userID = (Guid)currentUser.ProviderUserKey;
            }

            nplJobsBLL.ProcessEmployeer.ProcesEmployeerContactPerson pEmpContact = new nplJobsBLL.ProcessEmployeer.ProcesEmployeerContactPerson();
            pEmpContact.contactPersonID = 0;
            pEmpContact.employeerID = userID;
            pEmpContact.invoke();
            employeerContactPerson = pEmpContact.employeerContactPerson;

        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return employeerContactPerson;
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object SendMail(string toEmail, string subject, string empMail, string emailMessage)
    {
        string messageConf = "You mail has been sent";
        MembershipUser currentUser;
        try
        {
            employeerContactPerson = employeeContact();

            currentUser = (MembershipUser)HttpContext.Current.Session["userInfo"];
            if (currentUser != null)
            {
                userID = (Guid)currentUser.ProviderUserKey;
            }
            nplJobsBLL.ProcessEmployeer.ProcessSelectEmployeer emp = new nplJobsBLL.ProcessEmployeer.ProcessSelectEmployeer();
            emp.employeerID = userID;
            emp.invoke();
            employeer = emp.Employeer;


            string to = toEmail;
            using (MailMessage mm = new MailMessage())
            {

                string mailFromEmployer = "<br><br>Employeer Name: " + employeer[0].CompanyName +
                                            "<br>Contact Person: " + empMail +
                                            "<br>Email: " + employeerContactPerson[0].FirstName + employeerContactPerson[0].LastName +
                                            "<br>Address  : " + employeer[0].Address + "<br><br>";

                string nb = ConfigurationManager.AppSettings["CvDetailsNB"] != null ? ConfigurationManager.AppSettings["CvDetailsNB"].ToString() : string.Empty;

                StringBuilder sbMailMessage = new StringBuilder();
                sbMailMessage.Append(mailFromEmployer);
                sbMailMessage.Append(nb);

                try
                {
                    String fileName = System.Web.HttpContext.Current.Server.MapPath("~\\MailTemplate\\JobSeekerMail.html");
                    StreamReader file = new System.IO.StreamReader(fileName);
                    mm.To.Add(to);
                    mm.Body += file.ReadToEnd();
                    string detail = emailMessage.Trim();

                    detail += sbMailMessage.ToString();
                    string EmailSubject = subject;
                    mm.Subject = EmailSubject;
                    mm.Body = mm.Body.Replace("%details%", detail);
                    mm.IsBodyHtml = true;
                    file.Close();
                    new SmtpClient().Send(mm);
                }
                catch (Exception ex)
                {
                    messageConf = "Maiil cannot be sent.There is an internal problem.";
                    ErrorSignal.FromCurrentContext().Raise(ex);
                }
                finally
                {

                }

            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return new { Message = messageConf };
    }


}